class Solution(object):
    def matrixBlockSum(self, mat, k):
        m = len(mat)
        n = len(mat[0])
        for i in range(m):
            for j in range(n):
                if i > 0:
                    mat[i][j] += mat[i - 1][j]
                if j > 0:
                    mat[i][j] += mat[i][j - 1]
                if i > 0 and j > 0:
                    mat[i][j] -= mat[i - 1][j - 1]
        out = [[0 for _ in range(n)] for _ in range(m)]
        for i in range(m):
            for j in range(n):
                max_i = min(m - 1, i + k)
                max_j = min(n - 1, j + k)
                min_i = i - k
                min_j = j - k
                t = 0
                t += mat[max_i][max_j]
                if min_i > 0:
                    t -= mat[min_i - 1][max_j]
                if min_j > 0:
                    t -= mat[max_i][min_j - 1]
                if min_i > 0 and min_j > 0:
                    t += mat[min_i - 1][min_j - 1]
                out[i][j] = t
        return out


data = Solution()
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
k = 1
print(data.matrixBlockSum(mat, k))
